﻿using Ku.AppCore.Events;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Ku.AppCore.Controls
{
    public partial class MsgContentCtrl : UserControl
    {
        private const int MaxLineCount = 5000;
        private const int TimerInterval = 1000; // 修改定时器的间隔为1秒
        private StringBuilder messageBuffer = new StringBuilder();
        private Timer timer;

        public MsgContentCtrl()
        {
            InitializeComponent();
            timer = new Timer(UpdateOutputBox, null, 0, TimerInterval);
        }

        public void AppendMessage(string message)
        {
            var body = $"[{DateTime.Now.ToString("MM-dd HH:mm:ss")}] " + message + "\r\n";
            messageBuffer.Append(body);
        }

        private void UpdateOutputBox(object state)
        {
            try
            {

                if (messageBuffer.Length > 0)
                {
                    string text;
                    lock (messageBuffer)
                    {
                        text = messageBuffer.ToString();
                        messageBuffer.Clear();
                    }

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        string currentText = OutputBox.Text;
                        //string newText = currentText + text;
                        string[] lines = currentText.Split(new[] { "\r\n" }, StringSplitOptions.None);

                        if (lines.Length > MaxLineCount)
                        {
                            //int linesToRemove = lines.Length - MaxLineCount;
                            //newText = string.Join("\r\n", lines.Skip(linesToRemove));
                            OutputBox.Clear();
                        }

                        //OutputBox.Text = newText+"\r\n";
                        OutputBox.AppendText(text);

                        OutputBox.ScrollToEnd();
                    });
                }
            }
            catch
            {

            }
        }

        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            // 清空 TextBox
            this.OutputBox.Text = string.Empty;
        }
    }

}
